package top.songxs.gmall.seckill.biz.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.songxs.gmall.seckill.biz.SeckillGoodsBizService;
import top.songxs.gmall.seckill.entity.SeckillGoods;
import top.songxs.gmall.seckill.service.SeckillGoodsService;
import top.songxs.gmall.seckill.task.CachePreHotTask;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SeckillGoodsBizServiceImpl implements SeckillGoodsBizService {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public List<SeckillGoods> findSeckillGoodsList() {

        List<SeckillGoods> lists = seckillGoodsService.findSeckillGoodsList();
        return lists;
    }

    @Override
    public SeckillGoods findSeckillGoodsBySkuId(Long skuId) {
        //从本地缓存中拿
        ConcurrentHashMap<Long, SeckillGoods> localCache = CachePreHotTask.LOCAL_CACHE;
        SeckillGoods goods = localCache.get(skuId);
        if (goods == null){
            //如果本地缓存中不存在，需要把redis缓存中的数据拿出来同步到本地缓存中
            String redisGoodsKey = seckillGoodsService.buildRedisGoodsKey();
            List<Object> values = redisTemplate.opsForHash().values(redisGoodsKey);
            values.stream().forEach(obj->{
                String jsonString = obj.toString();
                SeckillGoods seckillGoods = JSON.parseObject(jsonString, SeckillGoods.class);
                localCache.put(seckillGoods.getSkuId(),seckillGoods);
            });
        }
        goods = localCache.get(skuId);
        return goods;
    }
}
